ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular CLI tutorial

The Angular CLI is a command-line interface for Angular developed by the Angular Team. This tool helps us quickly get started with creating the Angular application. In this tutorial, we will learn how to create and manage an Angular app using the Angular CLI commands. We will be covering commands like ng new, ng generate component, ng generate directive & ng generate pipe, etc.

What is Angular CLI

The Angular CLI is a command-line tool that allows us to create, develop, scaffold, and manage Angular applications from a command shell.

Angular CLI takes care of the time-consuming and error-prone task of creating and configuring the initial application. It also helps us quickly add new components, directives, and modules.

Using Angular CLI, you can

  1. Create a new Angular Project using a single command with all the initial default configurations. It sets up the Routes, type of style sheets to be used, whether to use stand alone components etc at the time of creation of the Project.
  2. We can add Components, Directives, Pipes, Services & Modules etc to it using few commands.
  3. It helps us to compile and build the application for distribution.
  4. It also has a development server, which helps us run, test and debug the application during the development phase. A single command (“ng serve“) compiles our application, starts a web server, and runs our application.

Angular Vs. Angular CLI

Angular is a complete framework that helps build single-page client applications. It consists of core functionalities that you need to develop a client application. It contains various libraries and tools to help us do that.

Angular CLI is just a command-line tool. It contains lots of commands that make it easier to work with the Angular framework.

For example, using the command “ng new,” we can create a new Angular project within a few minutes.

How to Install Angular CLI

We install the Angular CLI using the following npm command.

                              

npm install -g @angular/cli@latest
                            
                        

The above command installs the latest version of Angular CLI on your machine. Note that we have used the -g flag (which stands for global) to install the Angular CLI system-wide so you can use it in all projects.

image

Angular CLI Versions

Since Angular Version 6, the Angular CLI follows the same Version No as the Angular. Hence for Angular 7, the corresponding version of the Angular CLI is 7.

The Angular CLI version 1.7 was for Angular 5, and Angular CLI 1.4 was for Angular 4

You can keep track of the latest Angular CLI release from Angular CLI release information.

Angular CLI Version Check

You can find out the Current Installed Angular CLI Version by Using the Command

                              

ng --version
                            
                        

The latest version as of writing this article is 7.0.6. The command above also gives the version of the node installed in your system.

image

Angular CLI Commands

Commad Alias Description
help Help message shows the List of available commands and their short descriptions.
version v Find out the version of the Angular CLI Installed
new n Creates a new folder (Workspace) and ads the initial Angular app. Note that you can create multiple apps in a single folder (Workspace)
add Adds the npm package to the workspace and configure the default app project to use that library.
generate g Generates and/or modifies files based on a schematic.
update Updates your application and its dependencies
serve s Builds and serves your app, rebuilding on file changes.
run Runs a custom target defined in your project.
build b The Compiles the Angular app into an output directory ( Default is dist)
test t Runs unit tests in a project.
e2e e Builds and serves an Angular app, then runs end-to-end tests using Protractor.
config Retrieves or sets Angular configuration values.
doc d Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
lint i Runs linting tools on Angular app code in a given project folder.
xi18n Extracts i18n messages from source code.

Getting Help

                              
 
ng help
 
                            
                        

Getting help on individual commands us the syntax ng [command name] --help. For Example

                              

ng add --help       //help on add command
ng new --help       //help on new command  
 
                            
                        

Creating the Application with ng new

The ng new command is used to create new folder and creates an App with the provided name.

                              

ng new 
 
                            
                        

The command will ask you

  1. What name would you like to use for the project?
    Enter the name of the project here. “GettingStarted”
  2. Would you like to add Angular Routing?
    Answer this as Yes unless you do not want to add Angular Routing.
  3. Which stylesheet format would you like to use?
    You arrow keys to select the available options from CSS, SCSS, SASS, LESS, and Stylus

The above command will create a folder GettingStarted and copies all the required dependencies and configuration settings. The Angular CLI does the following

  1. Creates a new directory GettingStarted is created
  2. Downloads and installs Angular libraries and any other dependencies
  3. Installs and configures TypeScript.
  4. Installs and configures Karma & Protractor for testing
  5. Initialises the Git.

Running the Application

To run the application cd into the folder and run either ng server or use npm start (which runs the ng serve behind the scene)

                              

cd gettingStarted
ng serve         // or npm start  
                            
                        

Now open the browser and enter the URL http://localhost:4200/ and you should be able to see Welcome to GettingStarted! Message

You can stop the app by pressing ctrl-c

ng new options

Options Alias DESCRIPTION Value Type Default Value
--collection -c A collection of schematics to use in generating the initial application. String
--commit Initial git repository commit information. boolean true
--create-application Create a new initial application project in the 'src' folder of the new workspace. When false, creates an empty workspace with no initial application. You can then use the generate application command so that all applications are created in the projects folder
--defaults Disable interactive input prompts for options with a default. boolean false
--directory The directory name to create the workspace in string
--dry-run -d Run through and reports activity without making any changes. boolean false
--force -f Forces overwriting of any existing files in the project folder boolean false
--help Shows a help message for this command in the console boolean
--inline-style -s Use inline style rather than the external StyleSheet file. does not create external Stylesheets boolean false
--inline-template -t Does not create an external template file for the component. Specifies if the template will be in the ts file. boolean false
--interactive Enable interactive input prompts boolean true
--minimal Installs a minimal set of features. does not create test files. boolean false
--new-project-root The path where new projects will be created, relative to the new workspace root. string projects
--package-manager The package manager used to install dependencies. npm | yarn | pnpm | cnpm
--prefix -p The prefix to apply to generated selectors for the initial project.
--routing Generates a routing module. If the option is not specified, it will ask for the confirmation
--skip-git -g Do not initialize a git repository. boolean false
--skip-install Do not install dependency packages. false
--skip-tests -S Do not generate "spec.ts" test files for the new project.
--strict Creates a workspace with stricter type checking and stricter bundle budgets settings. This setting helps improve maintainability and catch bugs ahead of time boolean true
--style The file extension or preprocessor to use for style files. css | scss | sass | less
--view-encapsulation Specifies the view encapsulation strategy. Emulated | None | ShadowDom Emulated

ng new example

                              
 
//creates with new project with Style CSS
ng new gettingStarted --routing  --style CSS
 
//creates the new project with HelloWorld_root as the selector
ng new HelloWorld --routing  --style CSS -p HelloWorld
 
                            
                        

ng generate

                              

ng generate <schematic> [options]
ng g <schematic> [options]
                            
                        

ng generate or (ng g) is used to generate components , module , class , pipes & directives , etc. The following tables show the list of artifacts that can be generated.

schematic Syntax DESCRIPTION
appShell ng g appShell [options] Generate an App shell. Read about App Shell from here
application ng g application [options] Generates an application
class ng g class [options] Generates Class file
component ng g component [options] Generates a component
directive ng g directive [options] Generates a Directive
enum ng g enum [options] Generates an enum
guard ng g guard [options] Generates a Guard Component
interface ng g interface [options] Generates an Interface
library ng g library [options] Generates a Library
module ng g module [options] Generates a Module
pipe ng g pipe [options] Generates a Pipe
service ng g service [options] Generates a Service class
serviceWorker ng g serviceWorker [options] Generates a Service worker
universal ng g universal [options] Generates a Universal

Common options

OPTION Alias Default DESCRIPTION
--defaults=true|false false When true, disables interactive input prompts for options with a default
--dryRun=true|false -d false When true, run through and report activity without writing out results.
--force=true|false -f false When true, force overwriting of existing files
--help=true|false|json|JSON false Shows a help message for this command in the console.
--interactive=true|false false When false, disables interactive input prompts.

Component

The following command generates the component.

ng g component <name> [options]

Examples

ng g component Hello

The above command does the following

  1. Creates the Hello folder under the src/app folder
  2. Create the HelloComponent along with CSS, Spec & Template file under the Hello folder
  3. Imports the HelloComponent in the root module and adds it to the declarations array
  4. The CSS selector use the format app-<name>. i.e app-hello

ng g component --flat Hello does not create the hello folder. The component is created in the src/app folder.

ng g component --flat hello/hello creates the component under src/app/hello folder

ng g component --export hello adds the component to the exports metadata array of the module.

ng g component --prefix=myapp hello uses the CSS selector as myapp-hello.

ng g component --selector=hi --force hello uses the selector as hi

generate component inside module

ng g module account generates the code for account module

ng g component --module=account account/hello adds the component to the account module

The following is the list of all available options

OPTION Alias Default DESCRIPTION
--changeDetection= Default|OnPush -c Default Specifies the change detection strategy.
--entryComponent= true|false false Specifies if the component is an entry component of declaring module.
--export=true|false false Specifies if declaring module exports the component.
--flat= true|false false Flag to indicate if a directory is created.
--inlineStyle= true|false -s false Specifies if the style will be in the ts file.
--inlineTemplate=true|false -t false Specifies if the template will be in the ts file.
--lintFix= true|false false Specifies whether to apply lint fixes after generating the component.
--module= module -m root module Allows specification of the declaring module.
--prefix= prefix -p The prefix to apply to generated selectors.
--project= project The name of the project.
--selector= selector The selector to use for the component.
--skipImport= true|false false Flag to skip the module import.
--spec= true|false true Specifies if a spec file is generated.
--styleext= styleext css The file extension to be used for style files
--viewEncapsulation= Emulated| Native| None| ShadowDom -v Emulated Specifies the view encapsulation strategy.

Directive

ng g directive <name> [options] is used to generate the directive. For Example ng g directive Some generates the Some.Directive.ts. The following code is generated. It also generates the some.directive.spec.ts

                              

import { Directive } from '@angular/core';
 
@Directive({
  selector: '[appSome]'
})
export class SomeDirective {
 
  constructor() { }
 
}
 
                            
                        

The above command does not create the folder. You can use the ng g directive directive/Some, which will create the directive under the folder directive.

You can use the command ng g directive --flat=false Some, which will create the directive under the folder Some (folder name is same as the directive name)

You can use the --force flag to force overwriting of the files, if the files already exists

Use the--module flag to add the directive to a module other than the root module.

Use the --prefix or --selector flag to change the CSS Selctor.

You can use the --export & --skipImport to add the directive to exports and imports metadata of the module

The following is the complete list of available options

OPTION Alias Default DESCRIPTION
--export=true|false false Specifies if declaring module exports the component.
--flat= true|false true Flag to indicate if a directory is created.
--lintFix= true|false false Specifies whether to apply lint fixes after generating the component.
--module= module -m root module Allows specification of the declaring module.
--prefix= prefix -p The prefix to apply to generated selectors.
--project= project The name of the project.
--selector= selector The selector to use for the component.
--skipImport= true|false false Flag to skip the module import.
--spec= true|false true Specifies if a spec file is generated.

Pipe

ng generate pipe <name> [options] is used to generate the pipe. For Example, ng g pipe Date generates the date.pipe.ts. The following code is generated. It also generates the date.pipe.ts.spec.ts

                              

import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({
  name: 'date'
})
export class DatePipe implements PipeTransform {
 
  transform(value: any, args?: any): any {
    return null;
  }
 
}
 
                            
                        

The above command does not create the folder. You can use the ng g pipe pipes/Date, which will create the pipe under the folder pipes.

You can use the command ng g pipe --flat=false Date, which will create the pipe under the folder Date (folder name is the same as the pipe name)

You can use the --force flag to force overwriting of the files, if the files already exists

Use the--module flag to add the pipe to a module other than the root module.

You can use the --export & --skipImport to add the directive to exports and imports metadata of the module

Use the--module flag to add the pipe to a module other than the root module.

The following is the complete list of available options

OPTION Alias Default DESCRIPTION
--export=true|false true Specifies if declaring module exports the component.
--flat= true|false true Flag to indicate if a directory is created.
--lintFix= true|false false Specifies whether to apply lint fixes after generating the component.
--module= module -m root module Allows specification of the declaring module.
--project= project The name of the project.
--skipImport= true|false false Flag to skip the module import.
--spec= true|false true Specifies if a spec file is generated.

Service

ng generate service <name> [options] is used to generate the service. For Example ng g service Data generates the data.service.ts & data.service.ts.spec.ts. The following is the sample code generated by the command

                              

import { Injectable } from '@angular/core';
 
@Injectable({
  providedIn: 'root'
})
export class DataService {
 
  constructor() { }
}
 
                            
                        

The above command does not create the folder. You can use the ng g service services/Data, which will create the service under the folder services.

You can use the command ng g service --flat=false Data, which will create the service under the folder Data (folder name is same as the service name)

OPTION Alias Default DESCRIPTION
--flat= true|false true Flag to indicate if a directory is created.
--lintFix= true|false false Specifies whether to apply lint fixes after generating the component.
--project= project The name of the project.
--spec= true|false true Specifies if a spec file is generated.

class

ng generate class <name> [options] is used to generate the class. For Example ng g class customer generates the customer.ts in the current folder. The following is the sample code generated by the command

                              

export class Customer {
}
                            
                        

Use the command ng g class class/customer to create the class under the class folder.

OPTION Alias Default DESCRIPTION
--project= project The name of the project.
--spec= true|false true Specifies if a spec file is generated.
--type=type default Specifies the type of class

Module

use the ng g module <name> [options] command to generate the module. For Example ng g module account generates the account module under the folder src/app/account. The following code is generated

                              

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
 
@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class AccountModule { }
                            
                        

ng g module account --module=app generates the account module and adds it to the imports metadata array of AppModule

ng g module account --routing=true --force. The --force flag overwrites the previously generated files. The --routing=true also creates the account-routing.module. The routes are registered with the forChild(routes)

ng g module account --force --routing=true --routingScope=Root registers the routes with the forRoot(routes)

Adding Components, Pipes, Directives to module

You can add component, directive, pipe & services to module by using the flag --module=[ModuleName] and naming the component as [ModuleName]/[ComponentnNme].

For Example, The following commands creates the account module and adds the HelloComponent, SomeDirective, DataSerivce & DatePipe to the module

                              

ng g module account
ng g component --module=account account/hello
ng g directive --module=account --flat=false account/Some
ng g service --module=account --flat=false account/Data
ng g pipe --module=account --flat=false account/Date
 
                            
                        

The following is the list of all the available options

OPTION Alias Default DESCRIPTION
--flat= true|false false Flag to indicate if a directory is created.
--module=module -m Allows specification of the declaring module.
--project= project The name of the project.
--routing=true|false false Generates a routing module.
--routingScope=Child|Root child The scope for the generated routing.

ng update

The ng update command updates or upgrades the angular application and its dependencies to the latest version. Click on how to upgrade Angular to latest version for more information

Summary

The Angular CLI helps to increase productivity by helping us to quickly create the app and add the component, pipes, services & directives, etc to the module. The Angular CLI has a lot more commands like serve, build, test, lint, e2e etc, which help us to build and distribute the applications. We will cover those in one of the future tutorials.